<?php
/**
 * Base View class
 * Will handle all views, layouts and helper classes.
 */
namespace PUF;

class View {
	protected $title = '';
	
	protected $view = '';
	
	protected $viewVars = [];
	
	protected $Html = null;
	
	protected $layout = 'default';
	
	public function __construct() {
		Loader::getInstance()->load('Html');
		$this->Html = new Html();
	}
	
	public function Html() {
		return $this->Html;
	}
	
	/**
	 * Displays the layout and the corresponding view
	 */
	public function render($vars = []) {
		$this->viewVars = $vars;
		
		$Loader = Loader::getInstance();
		$Loader->load(
			'layouts/' . $this->getLayout(),
			[
				'type' => 'view',
				'vars' => ['View' => $this, 'Router' => Router::getInstance()] + $vars
			]
		);
	}
	
	public function showTitle() {
		echo $this->getTitle();
	}
	
	public function show() {
		$Loader = Loader::getInstance();
		$Loader->load(
			$this->getView(),
			[
				'type' => 'view',
				'vars' => ['View' => $this, 'Router' => Router::getInstance()] + $this->viewVars
			]
		);
	}
	
	public function getTitle() {
		return $this->title;
	}
	
	public function setTitle($title) {
		$this->title = $title;
	}
	
	public function getView() {
		return $this->view;
	}
	
	public function setView($view, $options = []) {
		$prefix = '';
		
		if (isset($options['plugin'])) {
			$prefix = "../lib/plugins/{$options['plugin']}/views/";
		}
		
		$this->view = $prefix . $view;
	}
	
	public function getLayout() {
		return $this->layout;
	}
	
	public function setLayout($layout, $options = []) {
		$prefix = '';

		if (isset($options['plugin'])) {
			$prefix = "../../lib/plugins/{$options['plugin']}/views/layouts/";
		}
		
		$this->layout = $prefix . $layout;
	}
	
	public function insertElement($element, $controller = null) {
		$url = "elements/{$element}";
		if ($controller) {
			$url = "{$controller}/{$url}";
		}
		
		$Loader = Loader::getInstance();
		$Loader->load($url, ['type' => 'view', 'vars' => ['View' => $this, 'Router' => Router::getInstance()] + $this->viewVars]);
	}
}